<style lang='scss' scoped>
@import "@css/style.scss";
.goods {
  background-color: $bgColor;
  margin-bottom: px2rem(25);
  &-scroll {
    overflow: hidden;
    overflow-y: auto;
  }
  &-item {
    background-color: #fff;
    padding: $marginSize;
    box-sizing: border-box;

    &-desc {
      width: 100%;
      &-name {
        font-size: $infoSize;
        line-height: px2rem(18);
        &-hint {
          color: $lineColor;
        }
      }
      &-data {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: $marginSize;

        &-price {
          font-size: $titleSize;
          color: $mainColor;
          font-weight: 500;
        }
        &-volume {
          font-size: $infoSize;
          color: $lineColor;
        }
      }
    }
  }
}
//垂直
.goods-list {
  &-item {
    display: flex;
    border-bottom: 1px solid $lineColor;

    .goods-item-img {
      width: px2rem(120);
      height: px2rem(120);
    }
    .goods-item-desc {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      padding: $marginSize;
    }
  }
}
//网格布局
.goods-grid {
  padding: $marginSize;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  &-item {
    width: 49%;
    border-radius: $radiusSize;
    margin-bottom: $marginSize;
    .goods-item-img {
      width: 100%;
    }
  }
}
//瀑布
.goods-waterfall {
  position: relative;
  margin: $marginSize;
  &-item {
    position: absolute;
    width: 49%;
    border-radius: $radiusSize;
    .goods-item-img {
      width: 100%;
    }
  }
}
</style>
<template>
  <div class="goods" ref="goods" @scroll="onScrollChange" :class="[layoutClass,{'goods-scroll':isScroll}]"  :style="{ height: goodsViewHeight }">
    <div
      class="goods-item"
      :class="layoutItemClass"
      ref="goodsItem"
      v-for="(item, index) in sortGoodsData"
      :key="index"
      :style="goodsItemStyles[index]"
      @click="onItemClick(item)"
    >
      <!-- 图片 -->
      <img class="goods-item-img" :src="item.img" :style="imgStyles[index]" />
      <!-- desc -->
      <div class="goods-item-desc">
        <p class="goods-item-desc-name">
          <!-- 是否为直营 -->
          <direct v-if="item.isDirect"></direct>
          <no-have v-if="!item.isHave"></no-have>
          <span
            class="text-line-2"
            :class="[!item.isHave ? 'goods-item-desc-name-hint' : '']"
            >{{ item.name }}</span
          >
        </p>
        <div class="goods-item-desc-data">
          <p class="goods-item-desc-data-price">
            ￥{{ item.price | priceValue }}
          </p>
          <p class="goods-item-desc-data-volume">销量{{ item.volume }}</p>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Direct from "./Direct.vue";
import NoHave from "./NoHave.vue";

export default {
  components: { Direct, NoHave },
  props: {
    //布局方式
    layoutType: {
      type: String,
      default: "1",
    },
    /**
     * 是否允许滑动
     */
    isScroll: {
      type: Boolean,
      default: true,
    },
    //排序规则
    sort:{
      type:String,
      default:'1'
    }
  },
  data() {
    return {
      //数据源
      dataSource: [],
      //排序数据
      sortGoodsData:[],
      maxImgHeight: 230,
      minImgHeight: 278,
      //图片样式集合
      imgStyles: [],
      //商品默认边距
      itemMarginSize: 8,
      //商品样式数组
      goodsItemStyles: [],
      //组件高度
      goodsViewHeight: "100%",
      //不同展示下的类名
      layoutClass: "goods-list",
      layoutItemClass: "goods-list-item",
      //滚动数
      scrollTopValue:0
    };
  },
  watch: {
    /**
     * 监听动态相应布局改变
     */
    layoutType() {
      this.initLayout();
    },
    /***
     * 监听sort改变
     */
    sort:function () {
      this.setSortGoodsData();
    }
  },
  activated(){
    /**
     * 定位页面滑动位置
     */
    this.$refs.goods.scrollTop=this.scrollTopValue;
  },
  mounted() {

    this.init();
  },
  methods: {
    /**
     * 设置布局动态
     */
    initLayout() {
      this.goodsViewHeight = "100%";
      this.goodsItemStyles = [];
      this.imgStyles = [];
      switch (this.layoutType) {
        case "1":
          this.layoutClass = "goods-list";
          this.layoutItemClass = "goods-list-item";
          break;
        case "2":
          this.layoutClass = "goods-grid";
          this.layoutItemClass = "goods-grid-item";
        case "3":
          this.layoutClass = "goods-waterfall";
          this.layoutItemClass = "goods-waterfall-item";
          this.initImgStyles();
          //dom创建完毕后调用这个方法去金乡流动布局
          this.$nextTick(() => {
            this.initWaterfall();
          });
        default:
          break;
      }
    },
    init() {
      this.$http.get("/goods").then((data) => {
        this.dataSource = data.list;
        //初始化默认1
        this.sortGoodsData=this.dataSource.slice(0);
        this.initLayout(); //设置布局
      });
    },
    //商品排序
    setSortGoodsData(){
      switch (this.sort) {
        case '1':
          //默认
          this.sortGoodsData=this.dataSource.slice(0);
          break;
        case '1-2':
          this.getSortGoodsDataFromKey('price');
          break;
        case '1-3':
          this.getSortGoodsDataFromKey('volume');
          break;
        case '2':
          this.getSortGoodsDataFromKey('isHave');
          break;
        case '3':
          this.getSortGoodsDataFromKey('isDirect');
          break;
      }
    },
    //进行排序方法
    getSortGoodsDataFromKey(key){
      this.sortGoodsData.sort((goods1,goods2)=>{
        let v1=goods1[key],v2=goods2[key];
        if(typeof v1==='boolean'){
          if(v1){
            return -1;
          }
          if(v2){
            return 1;
          }
          return 0;
        }
        if(parseFloat(v1)>=parseFloat(v2)){
          return -1;
        }
        return 1;
      });
    },
    //动态生成图片高度
    imgHeight() {
      let result = Math.floor(
        Math.random() * (this.maxImgHeight - this.minImgHeight) +
          this.minImgHeight
      );
      return result;
    },
    //初始化一个图片数组
    initImgStyles() {
      this.dataSource.forEach(() => {
        let imgHeight = this.imgHeight() + "px";
        this.imgStyles.push({
          height: imgHeight,
        });
      });
    },
    /**
     * 瀑布流
     */
    initWaterfall() {
      let $goodsItems = this.$refs.goodsItem;
      if (!$goodsItems) return;
      let leftHeightTotal = 0,
        rightHeightTotal = 0;
      //遍历所有的商品重新构建样式数组在修改样式
      $goodsItems.forEach(($el) => {
        let goodsItemStyle = {};
        let elHeight = $el.clientHeight + this.itemMarginSize;
        if (leftHeightTotal <= rightHeightTotal) {
          goodsItemStyle = {
            left: "0px",
            top: leftHeightTotal + "px",
          };
          leftHeightTotal += elHeight;
        } else {
          goodsItemStyle = {
            right: "0px",
            top: rightHeightTotal + "px",
          };
          rightHeightTotal += elHeight;
        }
        this.goodsItemStyles.push(goodsItemStyle);
      });
      //组件的高度设置，这里根据左右的最高进行设置
      if (!this.isScroll) {
        this.goodsViewHeight =
          leftHeightTotal > rightHeightTotal
            ? leftHeightTotal + "px"
            : rightHeightTotal + "px";
      }
    },
    //商品点击事件
    onItemClick(item){
      // 商品无库存
      if(!item.isHave){
        alert('该商品无库存');
        return;
      }
      this.$router.push({
        name:'goodsdetail',
        params:{
          goods:item,
          routerType:'push'
        }
      });
    },
    //监听滑动
   onScrollChange($event){
     this.scrollTopValue=$event.target.scrollTop;
    }
  },
  computed: {},
  
};
</script>